package org.orz.story.works.biz.clubhouse.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.orz.cloud.common.enums.AliveFlagEnum;
import org.orz.story.works.biz.clubhouse.model.dto.WorldCupScheduleDTO;
import org.orz.story.works.biz.clubhouse.model.resp.ListWorksWcScheduleResp;
import org.orz.story.works.biz.clubhouse.persistence.entities.WorksWcSchedule;
import org.orz.story.works.biz.clubhouse.persistence.mappers.WorksWcScheduleMapper;
import org.orz.story.works.biz.clubhouse.service.WorksWcSchedulesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WorksWcSchedulesServiceImpl implements WorksWcSchedulesService {
    @Autowired
    private WorksWcScheduleMapper worksWcScheduleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void downloadWorldCupScheduleJob() {
        String s = HttpUtil.get("http://apis.juhe.cn/fapigw/worldcup2022/schedule?key=" + "a893768793ef970cb88842af64495c2b");
        if(StrUtil.isBlank(s)){
            return;
        }
        // 保存到数据库里面
        WorldCupScheduleDTO dto = JSON.parseObject(s, WorldCupScheduleDTO.class);

        //把原有的数据都删除
        WorksWcSchedule deleteParam = new WorksWcSchedule();
        deleteParam.setAliveFlag(AliveFlagEnum.DELETED.getKey());
        deleteParam.setUpdateUser(0L);
        deleteParam.setUpdateDate(new Date());
        worksWcScheduleMapper.update(deleteParam, new LambdaQueryWrapper<WorksWcSchedule>()
                .eq(WorksWcSchedule::getAliveFlag, AliveFlagEnum.ALIVE.getKey()));

        //保存新的数据
        dto.getResult().getData().forEach(data -> {
            data.getSchedule_list().forEach(schedule -> {
                WorksWcSchedule scheduleData = packageScheduleData(data, schedule);
                worksWcScheduleMapper.insert(scheduleData);
            });
        });
    }

    @Override
    public List<ListWorksWcScheduleResp> listWorksWcSchedule() {
        LambdaQueryWrapper<WorksWcSchedule> wrapper = new LambdaQueryWrapper<WorksWcSchedule>()
                .eq(WorksWcSchedule::getAliveFlag, AliveFlagEnum.ALIVE.getKey());
        wrapper.orderByDesc(WorksWcSchedule::getId, WorksWcSchedule::getScheduleDate);
        List<WorksWcSchedule> worksWcSchedules = worksWcScheduleMapper.selectList(wrapper);
        if(CollUtil.isEmpty(worksWcSchedules)){
            return Collections.emptyList();
        }

        List<ListWorksWcScheduleResp> resultList = new ArrayList<>();
        ListWorksWcScheduleResp result = new ListWorksWcScheduleResp();
        for (int i = 0; i < worksWcSchedules.size(); i++) {
            int begin = i;
            WorksWcSchedule item = worksWcSchedules.get(i);
            do {
                if(i < worksWcSchedules.size() - 1 && worksWcSchedules.get(i + 1).getScheduleDate().getTime() == item.getScheduleDate().getTime()){
                    i++;
                } else {
                    break;
                }
            } while (true);
            result.setScheduleDateFormat(item.getScheduleDateFormat());
            result.setScheduleWeek(item.getScheduleWeek());
            List<ListWorksWcScheduleResp.Schedule> scheduleList = worksWcSchedules.subList(begin, i+1).stream().map(schedule -> {
                ListWorksWcScheduleResp.Schedule scheduleData = new ListWorksWcScheduleResp.Schedule();
                scheduleData.setId(schedule.getId());
                scheduleData.setDateTime(DateUtil.format(schedule.getDateTime(), "HH:mm"));
                scheduleData.setGroupName(schedule.getGroupName());
                scheduleData.setMatchTypeName(schedule.getMatchTypeName());
                scheduleData.setMatchTypeDes(schedule.getMatchTypeDes());
                scheduleData.setMatchDes(schedule.getMatchDes());
                scheduleData.setHostTeamLogoUrl(schedule.getHostTeamLogoUrl());
                scheduleData.setGuestTeamLogoUrl(schedule.getGuestTeamLogoUrl());
                scheduleData.setHostTeamName(schedule.getHostTeamName());
                scheduleData.setGuestTeamName(schedule.getGuestTeamName());
                scheduleData.setHostTeamScore(schedule.getHostTeamScore());
                scheduleData.setGuestTeamScore(schedule.getGuestTeamScore());
                return scheduleData;
            }).collect(Collectors.toList());
            result.setScheduleList(scheduleList);
            resultList.add(JSON.parseObject(JSON.toJSONString(result), ListWorksWcScheduleResp.class));
        }
        return resultList;
    }

    private WorksWcSchedule packageScheduleData(WorldCupScheduleDTO.Data data, WorldCupScheduleDTO.Schedule_list schedule) {
        WorksWcSchedule result = new WorksWcSchedule();
        result.setScheduleDate(data.getSchedule_date());
        result.setScheduleDateFormat(data.getSchedule_date_format());
        result.setScheduleWeek(data.getSchedule_week());
        result.setScheduleCurrent(data.getSchedule_current());
        result.setTeamId(schedule.getTeam_id());
        result.setDate(schedule.getDate());
        result.setDateTime(schedule.getDate_time());
        result.setHostTeamId(schedule.getHost_team_id());
        result.setGuestTeamId(schedule.getGuest_team_id());
        result.setHostTeamName(schedule.getHost_team_name());
        result.setGuestTeamName(schedule.getGuest_team_name());
        result.setHostTeamScore(schedule.getHost_team_score());
        result.setGuestTeamScore(schedule.getGuest_team_score());
        result.setMatchStatus(schedule.getMatch_status());
        result.setMatchDes(schedule.getMatch_des());
        result.setMatchType(schedule.getMatch_type());
        result.setMatchTypeName(schedule.getMatch_type_name());
        result.setMatchTypeDes(schedule.getMatch_type_des());
        result.setGroupName(schedule.getGroup_name());
        result.setHostTeamLogoUrl(schedule.getHost_team_logo_url());
        result.setGuestTeamLogoUrl(schedule.getGuest_team_logo_url());
        result.setCreateUser(0L);
        result.setCreateDate(new Date());
        return result;
    }
}
